#include <iostream>
#include <memory>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "Util.hpp"
#include "HttpServer.hpp"

void Usage(const std::string proc)
{
    std::cout << "\nUsage" << proc << " Port" << std::endl;
}

#define ROOT "./wwwroot"
#define HOMEPAGE "/index.html"

void HandlerHttpRequest(int sock)
{
	// 1、读取请求
    char buffer[10240];
    ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
    // 将接收到的数据直接当成字符串进行打印
    if(s > 0)
    {
        buffer[s] = '\0';
    }
    std::cout << buffer << "-----------------------" << std::endl;

    // 2、构建一个HTTP响应
    std::vector<std::string> vline;
    Util::cutString(buffer, "\n", &vline);
    std::vector<std::string> vblock;
    Util::cutString(vline[0], " ", &vblock);

    // 请求资源的路径
    std::string file = vblock[1];
    std::string target = ROOT;
    if(file == "/") file = HOMEPAGE;
    target += file;
    std::cout << target << std::endl;

    std::string content;
    std::ifstream in(target);
    if(in.is_open())
    {
        std::string line;
        while(std::getline(in, line))
        {
            content += line;
        }
        in.close();
    }

    std::string HttpResponse;
    if(content.empty()) 
    {
        HttpResponse = "HTTP/1.1 302 Found\r\n";
        HttpResponse += "Content-Type: text/html\r\n";
        HttpResponse += "Location: http://114.132.226.230:8080/a/b/404.html\r\n";
        HttpResponse += "Set-Cookie: 这是一个Cookie！\r\n";
    }
    else 
    {
        HttpResponse = "HTTP/1.1 200 OK\r\n";
        HttpResponse += ("Content-Length: " + std::to_string(content.size()) + "\r\n");
    }
    HttpResponse += "\r\n";
    HttpResponse += content;
    send(sock, HttpResponse.c_str(), HttpResponse.size(), 0);
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::unique_ptr<HttpServer> ptr(new HttpServer(atoi(argv[1]), HandlerHttpRequest));
    ptr->Start();

    return 0;
}